package itsm.isperp.module.messaging.handler.wechat;

import java.util.Hashtable;
import java.util.Map;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class ChatHandler extends TextWebSocketHandler {

	private Map<String, WebSocketSession> userMap = new Hashtable<>();

	@Override
	public void afterConnectionEstablished(WebSocketSession session)
			throws Exception {
		userMap.put(session.getId(), session);
		super.afterConnectionEstablished(session);
	}

	@Override
	public void handleTransportError(WebSocketSession session,
			Throwable exception) throws Exception {
		super.handleTransportError(session, exception);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session,
			CloseStatus status) throws Exception {
		userMap.remove(session);
		super.afterConnectionClosed(session, status);
	}

	@Override
	public void handleMessage(WebSocketSession session,
			WebSocketMessage<?> message) throws Exception {
		for (WebSocketSession webSocketSession : userMap.values()) {
			if (webSocketSession.isOpen()) {
				webSocketSession.sendMessage(message);
			}
		}
		super.handleMessage(session, message);
	}

}
